<?php
namespace app\share\controller;

use \app\share\model\Ping;
use think\Validate;

class PingAddress
{
    public function __construct()
    {
        $this->ping_address = new Ping();
    }
    /**
     * ping域名或者ip接口
     * @param  address   string    ip或者域名
     * @return  array
     */
    public function pingAddress()
    {
        $input = input();
        $validate = new Validate([
            ['address', 'require', 'Ping的地址不存在'],
        ]);
        if(!$validate->check($input))
        {
            return ['code'=>-1002,'msg'=>$validate->getError()];
        }
        return $this->ping_address->pingAddress($input['address']);
    }

    public function ping(){
        $input = input();
        $ip = $input['ip'];
        $ip_port = explode(':', $ip);
        if( filter_var( $ip_port[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ){        //IPv6
            $socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP);
        }elseif( filter_var( $ip_port[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ){    //IPv4
            $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        }else{
            return FALSE;
        }

        if( !isset($ip_port[1]) ){        //没有写端口则指定为80
            $ip_port[1] = '80';
        }
        $ok = socket_connect($socket, $ip_port[0], $ip_port[1]);
        socket_close($socket);
        return $ok;
    }
}